import { SqliteDB } from '@/driver/SqliteDB'

const BaseStore = {
    vm: null,
    db: null,
    entity: '',
    PAGE_MAX: 100000,
    init(vm) {
        this.vm = vm;
    },
    getDB() {
        if (null != this.db) {
            console.log('db file 2: ', this.vm.$store.db)
            return this.db;
        }
        console.log('db file: ', this.vm.$store.db)
        this.db = new SqliteDB(this.vm.$store.db, this.vm.$store.initScripts)
        return this.db;
    },

    insert(data) {
        this.getDB().insertData(this.entity, Object.assign({}, data));
    },

    update(data, condition) {
        this.getDB().updateData(this.entity, data, condition);
    },

    delete(condition) {
        let db = this.getDB();
        console.log('delete db link:', db)
        db.deleteData(this.entity, condition);
    },

    /**
     * 获取分页数据
     * @param page
     * @param pageSize
     * @param condition // const condition = "column_name = 'value'";
     * @param callback
     */
    getPagedData(page, pageSize, condition, callback) {
        let db =  this.getDB();
        let result = db.getPagedData(this.entity, page, pageSize, condition);
        result.then(data => {
            console.log('page result: ', data)
            let decodeData = []
            if (data.data) {
                data.data.forEach(row => {
                    let newRow = {}
                    Object.keys(row).map(key=> {
                        if (row[key]) {
                            newRow[key] = db.decodeVal(row[key])
                        } else {
                            newRow[key] = row[key]
                        }
                    })
                    decodeData.push(newRow)
                })
            }
            data.data = decodeData
            callback(data)
        })
    },

    /**
     * 获取所有列表.
     * @param condition
     * @param callback
     */
    getAll(condition, callback) {
        let db = this.getDB()
        let result = db.getAllData(this.entity, condition)
        result.then((data) => {
            let decodeData = []
            data.forEach(row => {
                let newRow = {}
                Object.keys(row).map(key=> {
                    if (row[key]) {
                        newRow[key] = db.decodeVal(row[key])
                    } else {
                        newRow[key] = row[key]
                    }
                })
                decodeData.push(newRow)
            })
            callback(decodeData)
        })
    },

    /**
     * 查询一条数据.
     * @param condition
     * @param callback
     */
    getOne(condition, callback) {
        this.getPagedData(1, 1, condition, (data) => {
            if (data.data && data.data.length > 0) {
                callback(data.data[0])
            } else {
                callback(null)
            }
        })
    }
}

export default BaseStore
